package cn.tudu.coolshark.controller;

import cn.tudu.coolshark.mapper.UserMapper;
import cn.tudu.coolshark.pojo.dto.UserDTO;
import cn.tudu.coolshark.pojo.vo.UserVO;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.web.bind.annotation.RequestBody;
import org.springframework.web.bind.annotation.RequestMapping;
import org.springframework.web.bind.annotation.RestController;

import javax.servlet.http.Cookie;
import javax.servlet.http.HttpServletResponse;
import javax.servlet.http.HttpSession;

@RestController
public class UserController {
    @Autowired(required = false)
    UserMapper mapper;
    @RequestMapping("/login")
    public int login(@RequestBody UserDTO userDTO, HttpServletResponse response, HttpSession session){
        System.out.println("userDTO = " + userDTO);
        UserVO userVO=mapper.selectByUsername(userDTO.getUsername());
        if(userVO!=null){
            if(userVO.getPassword().equals(userDTO.getPassword())){

                if(userDTO.getRem()){
                    Cookie c1=new Cookie("username",userDTO.getUsername());
                    Cookie c2=new Cookie("password",userDTO.getPassword());
                            c1.setMaxAge(60*60*24);
                            c2.setMaxAge(60*60*24);
                            response.addCookie(c1);
                            response.addCookie(c2);
                }
                session.setAttribute("user",userVO);
                return 1;

            }
            return 3;
        }
        return 2;
    }

    @RequestMapping("/currntUser")
    public UserVO currntUser(HttpSession session){
        return (UserVO) session.getAttribute("user");
    }
    @RequestMapping("/logout")
    public void logout(HttpSession session){
        session.removeAttribute("user");
    }
}
